# !/usr/bin/env python
# -*- coding:utf-8 -*-

import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText

from loguru import logger


def send_plain(data, title=None):
    # 邮箱服务器地址
    # 发件人邮箱地址
    # 发件人邮箱密码(使用申请的客户端授权码代替)
    smtp_server = 'smtp.qq.com'
    from_addr = '83852084@qq.com'
    passwd = 'ruqbqiqjmnjhbgih'

    # 收件人邮箱地址
    to_addr = 'stockbing@icloud.com'
    # 构建邮件内容(参数:邮件内容; 类型-plain,html; 编码)
    msg = MIMEText(str(data), 'plain', 'utf-8')
    # 设置邮件主题
    if title is None:
        title = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    msg['Subject'] = Header(f'{title}', charset='utf-8')
    msg['from'] = from_addr
    msg['to'] = to_addr

    # 获取SMTP对象
    server = smtplib.SMTP_SSL(host=smtp_server, port=465)
    # 登录163邮箱服务器
    server.login(user=from_addr, password=passwd)
    # 发送邮件
    server.sendmail(from_addr=from_addr, to_addrs=to_addr, msg=msg.as_string())
    # 退出邮箱服务器
    server.quit()
    logger.info('邮件发送成功')


if __name__ == '__main__':
    send_plain('测试一下')
